package com.manor.im.dialog

import android.app.Dialog
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.*
import android.widget.PopupWindow
import android.widget.RadioButton
import androidx.core.content.ContextCompat
import androidx.fragment.app.FragmentManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.google.android.material.tabs.TabLayout
import com.lxj.xpopup.interfaces.OnSelectListener
import com.manor.common.CommonAppConfig
import com.manor.common.Constants
import com.manor.common.bean.ChatGiftBean
import com.manor.common.custom.blur.Blurred
import com.manor.common.dialog.AbsDialogFragment
import com.manor.common.http.HttpCallback
import com.manor.common.http.PitUtil
import com.manor.common.utils.ToastUtil
import com.manor.common.interfaces.CommonCallback
import com.manor.common.interfaces.OnItemClickListener
import com.manor.common.utils.*
import com.manor.im.R
import com.manor.im.adapter.ChatGiftCountAdapter
import com.manor.im.adapter.ChatGiftPagerAdapter
import com.manor.im.http.ImHttpConst
import com.manor.im.http.ImHttpUtil
import com.tencent.qcloud.tim.uikit.base.IUIKitCallBack
import com.tencent.qcloud.tim.uikit.modules.group.info.GroupInfoProvider
import com.tencent.qcloud.tim.uikit.modules.group.member.GroupMemberInfo
import kotlinx.android.synthetic.main.dialog_chat_gift_new.view.*

/**
 * 赠送礼物
 * @date  2020/7/16  11:30
 * @version 1.0
 */
class ChatGiftDialog : AbsDialogFragment(), View.OnClickListener, OnItemClickListener<String>, ChatGiftPagerAdapter.ActionListener, TabLayout.OnTabSelectedListener {
    private var mDrawable1: Drawable? = null
    private var mDrawable2: Drawable? = null
    private var mLiveGiftPagerAdapter: ChatGiftPagerAdapter? = null
    private var mChatGiftBean: ChatGiftBean? = null
    private var DEFAULT_COUNT = "1"
    private var mCount = DEFAULT_COUNT
    private var mLiveUid: String? = null
    private var mSessionId: String? = null
    private var mHandler: Handler? = null
    private var mLianCountDownCount = 0//连送倒计时的数字

    private var WHAT_LIAN = 100
    private var mShowLianBtn = false //是否显示了连送按钮

    private var mSendGiftCallback: HttpCallback? = null
    private var mActionListener: ActionListener? = null

    private var isFromGuard = false

    private var isFromGroup = false

    private var isFromCall = false

    private var mGiftCountPopupWindow: PopupWindow? = null//选择分组数量的popupWindow

    private var lastPos = 0
    private val energyList: MutableList<ChatGiftBean> = mutableListOf()//糖果
    private val ticketList: MutableList<ChatGiftBean> = mutableListOf()//嗨券

    private var energyCount = ""//糖果
    private var ticketCount = ""//嗨券
    private var groupId = ""
    private var toNick = ""
    private var mProvider: GroupInfoProvider? = null


    companion object {
        fun forward(fragmentManager: FragmentManager, uId: String, isGuard: Boolean,
                    showId: String = "", listener: ActionListener) {
            forward(fragmentManager, uId, isGuard, false, showId, "", listener)
        }

        fun forward(fragmentManager: FragmentManager, uId: String, isGuard: Boolean, isFromGroup: Boolean,
                    showId: String = "", groupId: String, listener: ActionListener) {
            forward(fragmentManager, uId, isGuard, isFromGroup, false, showId, groupId, listener)
        }

        fun forward(fragmentManager: FragmentManager, uId: String, isGuard: Boolean, isFromGroup: Boolean, isCall: Boolean,
                    showId: String = "", groupId: String, listener: ActionListener) {
            if (uId.isNullOrEmpty() && !isFromGroup) return
            if (groupId.isNullOrEmpty() && isFromGroup) return
            val fragment = ChatGiftDialog()
            val bundle = Bundle()
            bundle.putString(Constants.LIVE_UID, uId)
            //通话时送礼才传
            bundle.putString(Constants.CHAT_SESSION_ID, showId)
            bundle.putString(Constants.GROUP_ID, groupId)
            bundle.putBoolean(Constants.IS_GUARD, isGuard)
            bundle.putBoolean(Constants.IS_FROM_GROUP, isFromGroup)
            bundle.putBoolean(Constants.IS_FROM_CALL, isCall)

            fragment.arguments = bundle
            fragment.setActionListener(listener)
            fragment.show(fragmentManager, "ChatGiftDialog")
        }


    }


    override fun getDialogStyle(): Int = R.style.dialog2_sd

    override fun getLayoutId(): Int = R.layout.dialog_chat_gift_new

    override fun canCancel(): Boolean = true

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val bundle = arguments
        if (bundle != null) {
            mLiveUid = bundle.getString(Constants.LIVE_UID) ?: mLiveUid
            mSessionId = bundle.getString(Constants.CHAT_SESSION_ID) ?: mSessionId
            groupId = bundle.getString(Constants.GROUP_ID) ?: groupId
            isFromGuard = bundle.getBoolean(Constants.IS_GUARD, false)
            isFromGroup = bundle.getBoolean(Constants.IS_FROM_GROUP, false)
            isFromCall = bundle.getBoolean(Constants.IS_FROM_CALL, false)
        }
        return super.onCreateDialog(savedInstanceState)
    }

    override fun setWindowAttributes(window: Window?) {
        window?.setWindowAnimations(R.style.bottomToTopAnim)
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = if (isFromGroup) DpUtil.dp2px(378) else DpUtil.dp2px(330)
        params?.gravity = Gravity.BOTTOM
        window?.attributes = params
    }


    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        mProvider = GroupInfoProvider()
        Blurred.init(context)


//        mRootView.ivBackGround.setImageDrawable(ColorDrawable(Color.parseColor("#F2000000")))
//        val bitmap = mRootView.ivBackGround.drawable.toBitmap(ScreenUtils.getScreenWidth(),ScreenUtils.getScreenWidth())

//        val map = BitmapFactory.decodeResource(resources, R.mipmap.ic_dialog_black_bg)
//        val bp: Bitmap? = Blurred().startDefault(map)
//        mRootView.ivBackGround.setImageBitmap(bp)

        mRootView.llSelectUser.setGone(!isFromGroup)

        if (isFromGroup){
            mRootView.llSelectUser.isClickable = true
            mRootView.llSelectUser.isFocusable = true
        }

        mDrawable1 = ContextCompat.getDrawable(mContext, R.drawable.bg_chat_gift_send)
        mDrawable2 = ContextCompat.getDrawable(mContext, R.drawable.bg_chat_gift_send_2)
        mRootView.mViewPager.offscreenPageLimit = 5
        mRootView.mViewPager.addOnPageChangeListener(onPagerChangeListener)
        mRootView.mBtnSend.setOnClickListener(this)
        mRootView.mBtnSendLian.setOnClickListener(this)
        mRootView.mBtnChooseCount.setOnClickListener(this)
        mRootView.llSelectUser.setOnClickListener(this)
        mRootView.tvRecharge.setOnClickListener(this)
        mRootView.ivDismiss.setOnClickListener { dismiss() }
        mRootView.tabLayout.addOnTabSelectedListener(this)

        mHandler = object : Handler() {
            override fun handleMessage(msg: Message) {
                mLianCountDownCount--
                if (mLianCountDownCount == 0) {
                    hideLianBtn()
                } else {
                    if (mRootView.mLianText != null) {
                        mRootView.mLianText.text = mLianCountDownCount.toString() + "s"
                        if (mHandler != null) {
                            mHandler?.sendEmptyMessageDelayed(WHAT_LIAN, 1000)
                        }
                    }
                }
            }
        }

        loadData()
    }

    override fun onDestroy() {
        mActionListener = null
        mHandler?.removeCallbacksAndMessages(null)
        mHandler = null
        mGiftCountPopupWindow?.dismiss()
        ImHttpUtil.cancel(ImHttpConst.GET_GIFT_LIST)
        ImHttpUtil.cancel(ImHttpConst.SEND_GIFT)
        if (mLiveGiftPagerAdapter != null) {
            mLiveGiftPagerAdapter?.release()
        }
        mContext = null
        super.onDestroy()
    }

    private fun loadData() {
        ImHttpUtil.getGiftList(object : HttpCallback() {
            override fun onSuccess(code: Int, msg: String, info: String) {
                if (code == 0 && info.isNotEmpty()) {
                    val result = PitUtil.strGetFirst(info)

                    val obj: JSONObject? = JSON.parseObject(result)
                    val ob: JSONObject? = JSON.parseObject(obj?.getString("list"))
                    val list: MutableList<ChatGiftBean>? = JSON.parseArray(ob?.getString("neng"), ChatGiftBean::class.java)
                    val listX: MutableList<ChatGiftBean>? = JSON.parseArray(ob?.getString("shan"), ChatGiftBean::class.java)
                    //List<ChatGiftBean> list = JSON.parseArray(obj.getString("list"), ChatGiftBean.class);

                    list?.let {
                        energyList.clear()
                        energyList.addAll(it)
                        showGiftList(it)
                    }
                    listX?.let {
                        ticketList.clear()
                        ticketList.addAll(it)
                    }
                    energyCount = obj?.getString("coin") ?: ""
                    ticketCount = obj?.getString("money") ?: ""
                    mRootView.mCoin.text = energyCount
                }
            }

            override fun onFinish() {
                if (mRootView.mLoading != null) {
                    mRootView.mLoading.visibility = View.INVISIBLE
                }
            }
        })
    }

    private fun showGiftList(list: List<ChatGiftBean>) {
        mLiveGiftPagerAdapter = ChatGiftPagerAdapter(mContext, list)
        mLiveGiftPagerAdapter?.setActionListener(this)
        mRootView.mViewPager.adapter = mLiveGiftPagerAdapter
        val inflater = LayoutInflater.from(mContext)
        var i = 0
        val size = mLiveGiftPagerAdapter?.count ?: 0
        mRootView.mRadioGroup.removeAllViews()
        while (i < size) {
            val radioButton = inflater.inflate(R.layout.view_chat_indicator, mRootView.mRadioGroup, false) as RadioButton
            radioButton.id = i + 10000
            if (i == 0) {
                radioButton.isChecked = true
            }
            mRootView.mRadioGroup.addView(radioButton)
            i++
        }
    }


    private val onPagerChangeListener = object : ViewPager.OnPageChangeListener {
        override fun onPageScrollStateChanged(state: Int) {
        }

        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
            if (mRootView.mRadioGroup != null) {
                (mRootView.mRadioGroup.getChildAt(position) as RadioButton?)?.isChecked = true
            }
        }

        override fun onPageSelected(position: Int) {
        }

    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {
    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
        when (tab?.position) {
            0 -> {
                if (lastPos != 0) {
                    mLiveGiftPagerAdapter?.cancel()
                    showGiftList(energyList)
                    mRootView.mCoin.text = energyCount
                }
                lastPos = 0
            }
            1 -> {
                if (lastPos != 1) {
                    mLiveGiftPagerAdapter?.cancel()
                    showGiftList(ticketList)
                    mRootView.mCoin.text = ticketCount
                }
                lastPos = 1
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.mBtnSend, R.id.mBtnSendLian -> {
                sendGift()
            }
            R.id.mBtnChooseCount -> {
                showGiftCount()
            }
            R.id.tvRecharge -> {
                forwardMyCoin()
            }
            R.id.llSelectUser -> {
                doLoadMember()
            }
        }
    }


    private fun doLoadMember() {
        if (StringUtil.isEmpty(groupId))
            return

        mProvider?.run {
            loadGroupInfo(groupId,object : IUIKitCallBack{
                override fun onSuccess(data: Any?) {
                     val list: MutableList<GroupMemberInfo>? =   this@run.groupMembers

                    if (mContext != null)
                    list?.let {
                        MemberSearchDialog.load(mContext, it, OnSelectListener { position, text ->
                            it[position].apply {
                                mLiveUid = this.userId
                                val name = if (this.nameCard.notNull()) this.nameCard else this.nickName
                                toNick = name
                                mRootView.tvSelectUser.text = "送给  $name"
                                Glide.with( mRootView.ivSelectUser)
                                        .load(this.iconUrl)
                                        .circleCrop()
                                        .error(R.mipmap.icon_avatar_placeholder)
                                        .into(mRootView.ivSelectUser)
                            }
                        })
                    }
                }

                override fun onError(module: String?, errCode: Int, errMsg: String?) {
                        errMsg?.let { ToastUtil.show(it) }
                }

            })
        }


    }

    /**
     * 跳转到充值
     */
    private fun forwardMyCoin() {
        dismiss()
        if (mActionListener != null) {
            mActionListener?.onChargeClick()
        }
    }

    /**
     * 显示分组数量
     */
    private fun showGiftCount() {
        val v = LayoutInflater.from(mContext).inflate(R.layout.view_gift_count, null)
        val recyclerView = v.findViewById<View>(R.id.recyclerView) as RecyclerView
        recyclerView.setHasFixedSize(true)
        recyclerView.layoutManager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, true)
        val adapter = ChatGiftCountAdapter(mContext)
        adapter.setOnItemClickListener(this)
        recyclerView.adapter = adapter
        mGiftCountPopupWindow = PopupWindow(v, DpUtil.dp2px(70), ViewGroup.LayoutParams.WRAP_CONTENT, true)
        mGiftCountPopupWindow?.setBackgroundDrawable(ColorDrawable(Color.parseColor("#80000000")))
        mGiftCountPopupWindow?.isOutsideTouchable = true
        mGiftCountPopupWindow?.showAtLocation(mRootView.mBtnChooseCount, Gravity.BOTTOM or Gravity.RIGHT, DpUtil.dp2px(70),
                DpUtil.dp2px(40))
    }

    /**
     * 隐藏分组数量
     */
    private fun hideGiftCount() {
        if (mGiftCountPopupWindow != null) {
            mGiftCountPopupWindow?.dismiss()
        }
    }

    override fun onItemClick(bean: String?, position: Int) {
        mCount = bean ?: ""
        mRootView.mBtnChooseCount.text = bean
        hideGiftCount()
    }

    override fun onItemChecked(bean: ChatGiftBean?) {
        mChatGiftBean = bean
        hideLianBtn()
        mRootView.mBtnSend.isEnabled = true
        if (DEFAULT_COUNT != mCount) {
            mCount = DEFAULT_COUNT
            mRootView.mBtnChooseCount.text = DEFAULT_COUNT
        }
        if (bean?.type ?: 0 == ChatGiftBean.TYPE_DELUXE) {
            if (mRootView.mBtnChooseCount != null && mRootView.mBtnChooseCount.visibility == View.VISIBLE) {
                mRootView.mBtnChooseCount.visibility = View.INVISIBLE
                mRootView.mArrow.visibility = View.INVISIBLE
                mRootView.mBtnSend.background = mDrawable2
            }
        } else {
            if (mRootView.mBtnChooseCount != null && mRootView.mBtnChooseCount.visibility != View.VISIBLE) {
                mRootView.mBtnChooseCount.visibility = View.VISIBLE
                mRootView.mArrow.visibility = View.VISIBLE
                mRootView.mBtnSend.background = mDrawable1
            }
        }
    }

    /**
     * 赠送礼物
     */
    private fun sendGift() {
        mRootView.mBtnSendLian.isClickable = false
        KLog.e("sendGift", "mLiveUid = $mLiveUid , mSessionId = $mSessionId , " +
                "mChatGiftBean = $mChatGiftBean")
        if (isFromGroup) {
            if (StringUtil.isEmpty(mLiveUid)) {
                ToastUtil.show("请选择礼物接收人")
                return
            }
            if (StringUtil.isEmpty(groupId))
                return
        }
        if (TextUtils.isEmpty(mLiveUid) || TextUtils.isEmpty(mSessionId) || mChatGiftBean == null) {
            return
        }
        if (mSendGiftCallback == null) {
            mSendGiftCallback = object : HttpCallback() {
                override fun onSuccess(code: Int, msg: String, info: String) {
                    mRootView.mBtnSendLian.isClickable =true
                    if (code == 0) {
                        if (info.isNotEmpty()) {

                            if (StringUtil.isNotEmpty(msg)){
                                ToastUtil.show(msg)
                            }

                            val result = PitUtil.strGetFirst(info)
                            val obj = JSON.parseObject(result)
                            KLog.i("mSendGiftCallback#onSuccess", obj)
                            val coin = obj.getString("coin")
                            val money = obj.getString("money")
                            val u = CommonAppConfig.getInstance().userBean
                            if (u != null) {
                                //u.level = obj.getIntValue("level")
                                u.coin = coin
                            }

                            energyCount = coin
                            ticketCount = money


                            if (mRootView.mCoin != null) {
                                if (lastPos == 1) {
                                    mRootView.mCoin.text = money
                                } else {
                                    mRootView.mCoin.text = coin
                                }
                            }
                            if (mChatGiftBean?.type == ChatGiftBean.TYPE_NORMAL) {
                                showLianBtn()
                            }


                        }
                    } else {
                        hideLianBtn()
                        ToastUtil.show(msg)
                    }
                }

                override fun onError() {
                    super.onError()
                    mRootView.mBtnSendLian.isClickable = true
                }
            }
        }

        //后台发送IM
        mChatGiftBean?.run {
            ImHttpUtil.sendGiftIM(mLiveUid, mSessionId, id, mCount, isFromGuard, groupId, toNick, mSendGiftCallback)
        }

        //旧版客户端发送IM
//        mChatGiftBean?.run {
//            ImHttpUtil.retSendGift(mLiveUid, mSessionId, id, mCount, isFromGuard, groupId, toNick, object
//                : HttpCallback() {
//                override fun onSuccess(code: Int, msg: String?, info: String?) {
//                    if (code == 0) {
//                        if (StringUtil.isEmpty(info))
//                            return
//
//                        info?.let {
//
//                            val eventBean = JSONObject.parseObject(it).toJavaObject (ChatReceiveGiftBean::class.java)
//                            eventBean.isLocal = true
//                            eventBean.isCall = isFromCall
//
//
//                            //这是礼物消息
//                            EventBus.getDefault().post(GiftShowEvent(eventBean))
//
//
//                            mActionListener?.onGiftSend( eventBean.toFJson(), object : CommonCallback<Boolean>() {
//                                override fun callback(bean: Boolean?) {
//                                    if (bean == true) {
//                                        ImHttpUtil.sendGift(mLiveUid, mSessionId, id, mCount, isFromGuard, groupId, toNick, mSendGiftCallback)
//                                    }
//                                }
//
//                            })
//                        }
//
//
//                    } else{
//                        msg?.let { ToastUtil.show(it) }
//                    }
//                }
//
//            })
//            //ImHttpUtil.sendGift(mLiveUid, mSessionId, id, mCount, isFromGuard, groupId, toNick, mSendGiftCallback)
//        }


    }

    /**
     * 隐藏连送按钮
     */
    private fun hideLianBtn() {
        mShowLianBtn = false
        if (mHandler != null) {
            mHandler?.removeMessages(WHAT_LIAN)
        }
        if (mRootView.mBtnSendLian != null && mRootView.mBtnSendLian.visibility == View.VISIBLE) {
            mRootView.mBtnSendLian.visibility = View.INVISIBLE
        }
        if (mRootView.mBtnSendGroup != null && mRootView.mBtnSendGroup.visibility != View.VISIBLE) {
            mRootView.mBtnSendGroup.visibility = View.VISIBLE
        }
    }

    /**
     * 显示连送按钮
     */
    private fun showLianBtn() {
        if (mRootView.mLianText != null) {
            mRootView.mLianText.text = "5s"
        }
        mLianCountDownCount = 5
        if (mHandler != null) {
            mHandler?.removeMessages(WHAT_LIAN)
            mHandler?.sendEmptyMessageDelayed(WHAT_LIAN, 1000)
        }
        if (mShowLianBtn) {
            return
        }
        mShowLianBtn = true
        if (mRootView.mBtnSendGroup != null && mRootView.mBtnSendGroup.visibility == View.VISIBLE) {
            mRootView.mBtnSendGroup.visibility = View.INVISIBLE
        }
        if (mRootView.mBtnSendLian != null && mRootView.mBtnSendLian.visibility != View.VISIBLE) {
            mRootView.mBtnSendLian.visibility = View.VISIBLE
        }
    }

    interface ActionListener {
        fun onChargeClick()

        fun onGiftSend(info: String,call :CommonCallback<Boolean>)
    }

    fun setActionListener(actionListener: ActionListener) {
        mActionListener = actionListener
    }


}